import axios from 'axios'
import { ElLoading } from 'element-plus'
import { saveAs } from 'file-saver'
import Message from 'vue-m-message'
import { getToken } from '@/utils/auth.js'

let downloadLoadingInstance
const downloadUtils = {
  fileDownload: (url, fileName) => {
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  },
  ossDownload: (ossId) => {
    const fileUrl = `${import.meta.env.VITE_APP_BASE_API}/system/oss/download/${ossId}`
    downloadLoadingInstance = ElLoading.service({ text: '正在下载数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' })
    axios.get(fileUrl, {
      responseType: 'blob',
      headers: {
        Authorization: `Bearer${getToken()}`,
      },
    }).then(async (res) => {
      const isBlob = await blobValidate(res.data)
      if (isBlob) {
        const blob = new Blob([res.data], { type: 'application/octet-stream' })
        saveAs(blob, decodeURIComponent(res.headers['download-filename']))
      }
      else {
        await printErrMsg(res.data)
      }
      downloadLoadingInstance.close()
    })
  },
}

async function blobValidate(data) {
  return true
}

async function printErrMsg(data) {
  const resText = await data.text()
  const rspObj = JSON.parse(resText)
  const errorCode = {
    401: '认证失败，无法访问系统资源',
    403: '当前操作没有权限',
    404: '访问资源不存在',
    default: '系统未知错误，请反馈给管理员',
  }
  const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode.default
  Message.error(errMsg)
}

export default downloadUtils
